function fn(num) {
  console.log(num)
  return num
}

function fn2(num) {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve(num + 1)
    }, 1000)
  })
}

function* gen() {
  const num1 = yield fn2(10)
  const num2 = yield fn2(num1)
  const num3 = yield fn2(num2)

  return num3
}

const g = gen()
const next1 = g.next()
next1.value.then((res) => {
  const next2 = g.next(res)
  console.log(res)
  next2.value.then((res2) => {
    console.log(res2)
    const next3 = g.next(res2)
    next3.value.then((res3) => {
      console.log(res3)
    })
  })
})

// console.log(g.next()) // 返回一个对象 {value: 1, done: false}
// console.log(g.next()) // 返回一个对象 {value: 1, done: false}

// console.log(g.next()) // 返回一个对象 {value: 1, done: false}
// console.log(g.next()) // 返回一个对象 {value: 1, done: true}

// next函数支持传参
// 第一次传参数没有效果
//

function asyncToPromise(generatorFn) {
  const gen = generatorFn()

  function handleResult(result) {
    if (result.done) {
      return Promise.resolve(result.value)
    }

    return Promise.resolve(result.value).then((res) => {
      return handleResult(gen.next(res))
    })
  }

  try {
    return handleResult(gen.next())
  } catch (err) {
    return Promise.reject(err)
  }
}

const asyncPromise = asyncToPromise(gen)
asyncPromise.then((res) => {
  console.log(res)
})
